package com.tianxiabuyi.weixin.pay.base;

import com.tianxiabuyi.utils.JSONUtil;

import java.util.HashMap;
import java.util.Map;

public class WxPayBase {
    public String toJson() {
        return JSONUtil.toJson(this);
    }

    public Map toMap() {
        return JSONUtil.fromJson(JSONUtil.toJson(this), Map.class);
    }

    public static <T> T fromJson(String json, Class<?> c) {
        Map origMap = JSONUtil.fromJson(json, Map.class);
        if (origMap == null) {
            origMap = new HashMap();
        }
        WxPayBase obj = (WxPayBase) JSONUtil.fromJson(json, c);
        if (obj == null) {
            try {
                obj = (WxPayBase) c.newInstance();
            } catch (InstantiationException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
        Map map = (Map) origMap.get("json");
        if (map == null) {
            map = new HashMap();
        }
        return (T) obj;
    }

    public static <T> T fromMap(Map map, Class<?> c) {
        String json = JSONUtil.toJson(map);
        return fromJson(json, c);
    }

    public String toString() {
        return getClass().getName() + ":" + toJson();
    }
}